package core

import (
	"net/http"
	"net/url"
	"net/http/cookiejar"
	"io"
	"io/ioutil"
	"encoding/json"
)

const (
	BASE_URL  = "https://xueqiu.com/"
	LOGIN_URL = "https://xueqiu.com/snowman/login"
)

func Run() error {
	task := &Task{
		client: &http.Client{},
	}
	// 1. 进入主页面
	if err := task.pageMain(); err != nil {
		return err
	}

	// 登陆
	if err := task.login(); err != nil {
		return err
	}

	//抓帖子
	if err := task.timeline(); err != nil {
		return err
	}

	//抓取评论
	//if err := task.comments(); err != nil {
	//	return err
	//}
	return nil
}
func (t *Task) timeline() error {
	murl := "https://xueqiu.com/v4/statuses/user_timeline.json?page=1&user_id=1761234358"
	req, err := http.NewRequest("GET", murl, nil)
	if err != nil {
		return err
	}

	res, err := t.client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	buf , _ := ioutil.ReadAll(res.Body)

	comments := &TimeLineResponse{}
	err = json.Unmarshal(buf , comments)
	if err != nil {
		return err
	}
	
	return nil
}
func (t *Task) comments() error {
	murl := "https://xueqiu.com/statuses/comments.json?id=96663459&count=10&page=1"
	req, err := http.NewRequest("GET", murl, nil)
	if err != nil {
		return err
	}
	res, err := t.client.Do(req)
	buf, err := ioutil.ReadAll(res.Body)
	tag("comments", string(buf))
	return nil
}

type Task struct {
	cookies []*http.Cookie
	client  *http.Client
}

func (t *Task) login() error {
	req, err := t.NewRequest("POST", LOGIN_URL, nil)
	if err != nil {
		return err
	}

	data := url.Values{}
	data.Add("remember_me", "true")
	data.Add("username", "13469684066")
	data.Add("password", "hq6123549")
	data.Add("captcha", "")

	jar, err := cookiejar.New(nil)
	if err != nil {
		return err
	}

	login_url, err := url.Parse(LOGIN_URL)
	if err != nil {
		return err
	}
	jar.SetCookies(login_url, t.cookies)
	t.client.Jar = jar
	res, err := t.client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	t.cookies = res.Cookies()
	tag("login", LOGIN_URL, JsonEncode(t.cookies), res)
	return nil
}
func (t *Task) NewRequest(method, url string, rd io.Reader) (*http.Request, error) {
	req, err := http.NewRequest(method, url, rd)
	if err != nil {
		return req, err
	}
	for _, cookie := range t.cookies {
		req.AddCookie(cookie)
	}
	req.Header.Add("Host", "xueqiu.com")
	req.Header.Add("Origin", "https://xueqiu.com")
	req.Header.Add("Referer", "https://xueqiu.com")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36")
	req.Header.Add("X-Requested-With", "XMLHttpRequest")
	return req, nil
}

func (t *Task) pageMain() error {

	req, _ := http.NewRequest("GET", BASE_URL, nil)
	res, err := t.client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	t.cookies = res.Cookies()
	tag("pageMain", res)
	return nil
}
